<?php
namespace Core;

class TbRedis{
    private static $workredis;
    private function __construct() {

    }

    public static  function tbredis(){
        $redis_config = config('redis');
        $redis = new \Redis();
        if(!$redis->connect($redis_config['host'], $redis_config['port']))
        {
            echo "can not connect redis: \n";
            return;
        }
        if(!empty($redis_config['auth'])) $redis->auth($redis_config['auth']);
	    $redis->select($redis_config['db']);
        return $redis;
    }

    public static  function init($workid){
        if(!isset(self::$workredis[$workid]) || self::$workredis[$workid] ==null){
            $redis_config = config('redis');
            $redis = self::redisConnect($redis_config);
            if($redis === false)
            {
                echo "正在重新启动redis===============\n";
             //   exec('/root/tanba/redisStart.sh');
                sleep(2);
                $redis = self::redisConnect($redis_config);
                if(is_object($redis))echo "redis 启动成功============\n";
            }
            
            if(!empty($redis_config['auth'])){
                $redis->auth($redis_config['auth']);
            }
            $redis->select($redis_config['db']);
           // echo "\n --redis connect--:".$workid;
            self::$workredis[$workid]=$redis;
        }
        self::$workredis[$workid]->workerid = $workid;
        return self::$workredis[$workid];
    }
    
    public static function redisConnect($redis_config){
        $redis = new \Redis();
        if(!@$redis->connect($redis_config['host'], $redis_config['port'])){
            return false;
        }else{
            return $redis;
        }
    }


    public static  function close($workid){
          unset(self::$workredis[$workid]);
    }

}